package top.dyzmj.detty.core.utils;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 常量的基本实现类
 *
 * @author dongYu
 * @date 2021/11/19
 */
public class AbstractConstant<T extends AbstractConstant<T>> implements Constant<T> {

	private static final AtomicLong UNIQUE_ID_GENERATOR = new AtomicLong();

	private final int id;
	private final String name;
	private final long uniquifier;

	/**
	 * 构造方法
	 */
	protected AbstractConstant(int id, String name) {
		this.id = id;
		this.name = name;
		this.uniquifier = UNIQUE_ID_GENERATOR.getAndIncrement();
	}

	@Override
	public int id() {
		return id;
	}

	@Override
	public String name() {
		return name;
	}

	@Override
	public String toString() {
		return name();
	}

	@Override
	public boolean equals(Object obj) {
		return super.equals(obj);
	}

	@Override
	public int hashCode() {
		return super.hashCode();
	}

	@Override
	public int compareTo(T o) {
		if (this == o) {
			return 0;
		}

		AbstractConstant<T> other = o;
		int returnCode;

		returnCode = hashCode() - other.hashCode();
		if (returnCode != 0) {
			return returnCode;
		}

		if (uniquifier < other.uniquifier) {
			return -1;
		}

		if (uniquifier > other.uniquifier) {
			return 1;
		}
		throw new Error("failed to compare two different constants");
	}
}
